package com.may.ipersistence.config;

import com.may.ipersistence.io.Resource;
import com.may.ipersistence.pojo.Configuration;
import com.may.ipersistence.sqlSession.SqlSessionFactoryBuilder;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * @program: lagou
 * @description:
 * @author: Bobby.Ma
 * @create: 2020-10-31 14:51
 **/
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder(){
        this.configuration = new Configuration();
    }

    // 解析配置文件
    public Configuration parse(InputStream in) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(in);
        //拿到根节点
        Element root = document.getRootElement();
        //xpath 表达式，// 标识从根节点下寻找
        List<Element> dataSourceNodes = root.selectNodes("//dataSource/property");
        Properties dataSourceProp = dataSourceNodes.stream()
                .collect(Collectors.toMap(el -> el.attributeValue("name"),el -> el.attributeValue("value"),(o1,o2) -> o1,Properties::new));

        // c3p0 连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(dataSourceProp.getProperty("driverClass"));
        dataSource.setJdbcUrl(dataSourceProp.getProperty("jdbcUrl"));
        dataSource.setUser(dataSourceProp.getProperty("username"));
        dataSource.setPassword(dataSourceProp.getProperty("password"));
        configuration.setDataSource(dataSource);

        List<Element> mapperNodes = document.selectNodes("//mapper");
        for (Element el : mapperNodes){
            String mapperPath = el.attributeValue("resource");
            XMLMapperBuilder builder = new XMLMapperBuilder(configuration);
            builder.parse(Resource.getResourceAsStream(mapperPath));
        }
        return configuration;
    }
}
